var pageNum=1;
var pageSize=10;
$(document).ready(function(){	
	/*历史数据下选项卡切换选择事件*/
	$('#historyDataDetailUlId').on('click','li',function(){
		$(this).addClass("onlike").siblings().removeClass("onlike");//默认选中当前选项
		var index = $(this).index();
		if (index == 0) {
			$("#gasHistoryDataDivId").show();
			$("#gasHistoryChartDivId").hide();
			$.ajax({
		 		type : "post",
		 		url : "/historyData/queryHistoryGasDataDate",
		 		data: null,
		 		dataType:"json",
		 		headers: {"Content-Type": "application/json;charset=utf-8"},
		 		success : function(data) {	
		 			if (data) {
		 				$("#historyGasDataStartTime").val(data[0]);
						$("#historyGasDataEndTime").val(data[1]);
					}else{
						$("#historyGasDataStartTime").val(getStartCurrentDay());
						$("#historyGasDataEndTime").val(getEndCurrentDay());
					}
					pageNum=1; 
					pageSize=10;
					$("#historyGasDataPage").html("");
					$("#historyGasDataPage").show();
					getHistoryGasDataFn();
		 		},error: function(request) {
		 			layer.msg(networkErrorMsg, {time: 2000});
		 	     }
		 	})
		}
		if (index == 1) {
			$("#gasHistoryDataDivId").hide();
			$("#gasHistoryChartDivId").show();
			$.ajax({
		 		type : "post",
		 		url : "/historyData/queryHistoryGasDataDate",
		 		data: null,
		 		dataType:"json",
		 		headers: {"Content-Type": "application/json;charset=utf-8"},
		 		success : function(data) {	
		 			if (data) {
		 				$("#historyGasChartStartTime").val(data[0]);
						$("#historyGasChartEndTime").val(data[1]);
					}else{
						$("#historyGasChartStartTime").val(getStartCurrentDay());
						$("#historyGasChartEndTime").val(getEndCurrentDay());
					}
					getHistoryGasChartFn("qry");
		 		},error: function(request) {
		 			layer.msg(networkErrorMsg, {time: 2000});
		 	     }
		 	})
		}
		
	});
	
	$("#historyGasDataDeviceSelectId").text('全部');
	/*给气体历史数据设备的li绑定事件*/
	$('#historyGasDataDeviceSelectDiv').on('click','li',function(){
		$("#historyGasDataDeviceSelectDiv").val($(this).attr("name"));
		if($(this).text()){
		   $("#historyGasDataDeviceSelectId").text($(this).text()); 
		}			
		$("#historyGasDataDeviceSelectDiv").hide();   
	});
	$('#historyGasChartDl dd').on('click',function(){
		console.log($(this).text());
		getHistoryGasChartFn($(this).text());
	});
});

	function controlHistoryGasDataDeviceSelect(data){
		var node=$("#historyGasDataDeviceSelectDiv");
		if (node.is(':hidden')) {
			node.show();
		}else{
			node.hide();
		}
	};
	
	function getStartCurrentDay(){
		var day = new Date();
		day.setTime(day.getTime());
		var s = day.getFullYear()+"-" + initSt((day.getMonth()+1)) + "-" + initSt(day.getDate())
			+" "+initSt((day.getHours()-1))+":"+initSt(day.getMinutes())+":"+initSt(day.getSeconds());
		return s;
	};

	function getEndCurrentDay(){
		var day = new Date();
		day.setTime(day.getTime());
		var s = day.getFullYear()+"-" + initSt((day.getMonth()+1)) + "-" + initSt(day.getDate())
		+" "+initSt(day.getHours())+":"+initSt(day.getMinutes())+":"+initSt(day.getSeconds());
		return s;
	};
	function initSt(m){
		if(m<10){
			return "0"+m;
		}
		return m;
	}
	
	function cheackDate(startTime,endTime){/*0成功，1开始时间不能为空，2结束时间不能为空，3开始时间不能大于结束时间，4时间间隔不能超过5天*/
		var result = 0;
		if (startTime=="") {
			result = 1;
			return result;
		}
		if (endTime=="") {
			result = 2;
			return result;
		}
		var sTime = new Date(startTime.replace(/-/g, "\/"));
		var eTime = new Date(endTime.replace(/-/g, "\/"));
		if (sTime>eTime) {
			result = 3;
			return result;
		}
		if ((sTime+24*60*60*1000)<eTime) {
			result = 4;
			return result;
		}
		return result;
	};
	
	//分页
	function generatePagination(cp,tp,keyId){
		this.currentPage = Number(cp);
		this.totalPages = Number(tp);
		var jump_prev=currentPage>1?(currentPage-1):currentPage;
		var jump_next=(currentPage<totalPages)?(currentPage+1):totalPages;
		var pageList ="<a name='findPage' pageNum='"+jump_prev+"' class='front'><span></span></a>";
		var page_start = Number(currentPage)/5;
		if(page_start>1){
			pageList = getPageHtml(page_start*5-2,page_start*5+3,totalPages,pageList);
		}else{
			pageList = getPageHtml(1,6,totalPages,pageList);
		}
		pageList +="<a name='findPage' pageNum='"+jump_next+"' class='after'><span></span></a>";
		$("#"+keyId).html(pageList);
		if(keyId=="historyGasDataPage"){
			$("#historyGasDataPage").find("[name=findPage]").on("click",function(){
			   pageNum=$(this).attr("pageNum");  //获取链接里的页码  
			   getHistoryGasDataFn();
			}); 
		}
		
	}

	function getPageHtml(start,end,totalPages,pageList){
		for(var i=start;i<=end;i++){
			if(i<=totalPages){
				var temp =""
				if(i==currentPage){
					temp="<a name='findPage' pageNum='"+i+"' class='onlink'>"+i+"</a>";
				}else{
					temp="<a name='findPage' pageNum='"+i+"'>"+i+"</a>";
				}
				pageList+=temp;
			}
		}
		return pageList;
	}
	
	function qryHistoryGasDataFn(){
		pageNum=1;
		getHistoryGasDataFn();
	}
	
	/*获取历史气体数据的信息*/
	function getHistoryGasDataFn(){
		var startTime = $("#historyGasDataStartTime").val();
		var endTime = $("#historyGasDataEndTime").val();
		var timeResult = cheackDate(startTime,endTime);/*0成功，1开始时间不能为空，2结束时间不能为空，3开始时间不能大于结束时间，4时间间隔不能超过5天*/
		if (timeResult == 1) {
			layer.msg("开始时间不能为空！");
		}else if(timeResult == 2){
			layer.msg("结束时间不能为空！");
		}else if(timeResult == 3){
			layer.msg("开始时间不能大于结束时间！");
		}else if(timeResult == 4){
			layer.msg("时间间隔不能超过24小时！");
		}else{
			var dNo = $("#historyGasDataDeviceSelectId").text();
			if(dNo=="全部"){
				dNo="";
			}
			var params = {};
		 	params.startTime=startTime;
		 	params.endTime=endTime;
		 	params.deviceSerial=dNo;
		 	params.pageNum = pageNum;
		 	params.pageSize = pageSize;
		 	var loading = layer.load(2);
		 	$.ajax({
		 		type : "post",
		 		url : "/historyData/queryHistoryGasData",
		 		data: JSON.stringify(params),
		 		dataType:"json",
		 		headers: {"Content-Type": "application/json;charset=utf-8"},
		 		success : function(data) {	
		 			layer.close(loading);
		 			if(data.records){
	 					var html = "";
	 					var currentPage = Number(data.current);
						var totalPages = Number(data.pages);
						if(currentPage>=1 && totalPages>1){
							generatePagination(currentPage,totalPages,"historyGasDataPage");
						}else{
							$("#historyGasDataPage").html("");
						}
	 					var list = data.records;
	 					if (list.length >0) {	 						
	 						for (var i = 0; i < list.length; i++) {
	 							var no = i+1;
	 							var color = list[i].state==1?"red":list[i].state==2?"yellow":list[i].state==3?"grey":""
								html+='<tr >';
								html+='<td class="'+color+'">'+no+'</td>';
								html+='<td class="'+color+'">'+list[i].timeString+'</td>';
								html+='<td class="'+color+'">'+list[i].sensorAddress+'</td>';
								html+='<td class="'+color+'">'+list[i].gasName+'</td>';
								html+='<td class="'+color+'">'+list[i].gasConcentration+list[i].measurementUnit+'</td>';
								html+='<td class="'+color+'">'+list[i].desc+'</td>';
								html+='</tr>';
							}
						}
	 					$("#historyGasDataTableBoby").empty();
	 					$("#historyGasDataTableBoby").append(html);
		 			}
		 			
		 		},error: function(request) {
		 			layer.close(loading);
		 			layer.msg(networkErrorMsg, {time: 2000});
		 	     }
		 	})
		}
	};
	
	/*下载历史气体数据的信息*/
	function downLoadHistoryGasDataFn(){
		var startTime = $("#historyGasDataStartTime").val();
		var endTime = $("#historyGasDataEndTime").val();
		var timeResult = cheackDate(startTime,endTime);/*0成功，1开始时间不能为空，2结束时间不能为空，3开始时间不能大于结束时间，4时间间隔不能超过5天*/
		if (timeResult == 1) {
			layer.msg("开始时间不能为空！");
		}else if(timeResult == 2){
			layer.msg("结束时间不能为空！");
		}else if(timeResult == 3){
			layer.msg("开始时间不能大于结束时间！");
		}else if(timeResult == 4){
			layer.msg("时间间隔不能超过24小时！");
		}else{
			var dNo = $("#historyGasDataDeviceSelectId").text();
			if(dNo=="全部"){
				dNo="";
			}
			var params = {};
		 	params.startTime=startTime;
		 	params.endTime=endTime;
		 	params.deviceSerial=dNo;
		 	params.pageNum = pageNum;
		 	params.pageSize = pageSize;
			window.open("/historyData/downLoadGasDataEXL?param="+encodeURIComponent(JSON.stringify(params)));
		}
	};
	
	/*获取历史气体图表的信息*/
	function getHistoryGasChartFn(param){
		if (param=="qry") {
			var sensor = $("#historyGasChartDl").children().get(1);
			if(!sensor){
				layer.msg("未查询到设备编号列表！");
				return false;
			}
			param=sensor.textContent;
		}
		var startTime = $("#historyGasChartStartTime").val();
		var endTime = $("#historyGasChartEndTime").val();
		var timeResult = cheackDate(startTime,endTime);/*0成功，1开始时间不能为空，2结束时间不能为空，3开始时间不能大于结束时间，4时间间隔不能超过5天*/
		if (timeResult == 1) {
			layer.msg("开始时间不能为空！");
		}else if(timeResult == 2){
			layer.msg("结束时间不能为空！");
		}else if(timeResult == 3){
			layer.msg("开始时间不能大于结束时间！");
		}else if(timeResult == 4){
			layer.msg("时间间隔不能超过24小时！");
		}else{
			var params = {};
		 	params.startTime=startTime;
		 	params.endTime=endTime;
		 	params.deviceSerial=param;
		 	var loading = layer.load(2);
		 	$.ajax({
		 		type : "post",
		 		url : "/historyData/queryHistoryGasChart",
		 		data: JSON.stringify(params),
		 		dataType:"json",
		 		headers: {"Content-Type": "application/json;charset=utf-8"},
		 		success : function(data) {	
		 			layer.close(loading);
	 				if(data.title){
	 					var html = "";
	 					var chartData = data;
	 					// 基于准备好的dom，初始化echarts实例
	 			        var myChart = echarts.init(document.getElementById('historyGasChartImgDiv'));
	 			        option = {
	 			    		    title: {
	 			    		        text: chartData.title,
	 			    		        textStyle: {
		 			  	                color: '#fff',
		 			  	                fontSize:16,
		 			  	            },
		 			  	            padding: [10, 10]
	 			    		    },
	 			    		    tooltip: {
	 			    		        trigger: 'axis',
	 			    		        backgroundColor:'rgba(255,255,255,0.8)',
	 			  		            borderColor:'gray',
	 			  		        	textStyle:{
	 			  		        		color:'black',
	 			  		        	}
	 			    		    },
	 			    		    legend: {
	 			    		        data:chartData.legendData,
	 			    		        textStyle: {
	 			    		        	color: '#fff',
	 			    		        	fontSize:14
	 			    		        },
	 			    		       padding: [10, 10]
	 			    		    },
	 			    		    grid: {
	 			    		        left: '5%',
	 			    		        right: '5%',
	 			    		        bottom: '5%',
	 			    		        containLabel: true
	 			    		    },
	 			    		    xAxis: {
	 			    		        type: 'category',
	 			    		        boundaryGap: false,
	 			    		        data: chartData.xAxis.data,
//	 			    		        axisLabel: {
//	 			    		            rotate: 60,
//	 			    		        },
	 			    		       axisLabel: {
	 			                      textStyle: {
	 			                          color: '#fff',
	 			                          fontSize:14
	 			                      },
	 			                      rotate: 60,
	 			                      showMaxLabel: true
	 			                  },
	 			                  axisLine: {
	 			                      lineStyle: {
	 			                          color: '#fff'	 			                          
	 			                      }  
	 			                  },
	 			    		    },
	 			    		    yAxis: {
	 			    		        type: 'value',
	 			    		        axisLabel: {
	 			  		            textStyle: {
	 			  		                color: '#fff',
	 			  		                fontSize:14,
	 			  		            }
	 			  		        },
	 			  		        axisLine: {
	 			                      lineStyle: {
	 			                          color: '#fff'
	 			                      }  
	 			                  }
	 			    		    },
	 			    		    series: chartData.seriesData
	 			    	};
	 			       // 使用刚指定的配置项和数据显示图表。
	 			        myChart.setOption(option,true);
	 				}
		 			
		 		},error: function(request) {
		 			layer.close(loading);
		 			layer.msg(networkErrorMsg, {time: 2000});
		 	     }
		 	})
		}
	};
	